package com.deepexps.security.controller;


import com.deepexps.security.commen.Message;
import com.deepexps.security.commen.ParameterException;
import com.deepexps.security.commen.ResponseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.TypeMismatchException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.AccessDeniedException;


/**
 * @author moyi
 */
@Controller
public class BaseController {
	private static final Logger log= LoggerFactory.getLogger(BaseController.class);

	@ExceptionHandler
	@ResponseBody
	public Object handle(Exception e, HttpServletRequest request,HttpServletResponse response) throws IOException {
		StackTraceElement[] ste=e.getStackTrace();
		log.error("message:"+e.getMessage());
		for(int i=0;i<ste.length&&i<=3;i++) {
			log.error(",class:"+ste[i].getClassName()+",methodName:"+ste[i].getMethodName()+",lineNumber="+ste[i].getLineNumber());
		}
		if(e instanceof TypeMismatchException|| e instanceof MissingServletRequestParameterException|| e instanceof ParameterException){
			return ResponseResult.getError(Message.HTTP_PARAM_ERROR);
		}else if(e instanceof AccessDeniedException){
			return ResponseResult.getError(Message.HTTP_ACCESS_DENIED);
		}else{
			return ResponseResult.getError(Message.HTTP_SERVER_ERROR);
		}

	}
    protected String getRequestClientId(){
    	HttpServletRequest request=this.getHttpServletRequest();
    	String userAgent=request.getHeader("User-Agent");
    	//String ip=request.getRemoteAddr();
    	String ip="";
    	return String.valueOf((userAgent+ip).hashCode());
    }
    protected String getUserId(){
    	HttpServletRequest request=this.getHttpServletRequest();
    	Object userId= request.getAttribute("userId");
    	return userId==null?null:userId.toString();
    }
	protected HttpServletRequest getHttpServletRequest() {
		return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
	}
}
